﻿
using SqlSugar;
using YY.Admin.Core.Session;

namespace YY.Admin.Services.Service.User
{
    public class SysUserService : ISysUserService, ISingletonDependency
    {
        private readonly ISysOrgService _sysOrgService;
        private readonly ISqlSugarClient _dbContext;
        public SysUserService(ISysOrgService orgService, ISqlSugarClient dbContext)
        {
            _sysOrgService = orgService;
            _dbContext = dbContext;
        }
        public async Task<List<SysUser>> GetUsersAsync()
        {
            await Task.Delay(200);
            return new List<SysUser>();
        }

        public async Task<SqlSugarPagedList<UserOutput>> PageAsync(PageUserInput input)
        {
            var currentUser = AppSession.CurrentUser;
            //获取子节点Id集合(包含自己)
            var orgList = await _sysOrgService.GetChildIdListWithSelfById(input.OrgId);
            return await _dbContext.Queryable<SysUser>()
                       .LeftJoin<SysOrg>((u, a) => u.OrgId == a.Id)
                       .LeftJoin<SysPos>((u, a, b) => u.PosId == b.Id)
                       .Where(u => u.AccountType != AccountTypeEnum.SuperAdmin)
                       .WhereIF(input.OrgId > 0, u => orgList.Contains(u.OrgId))
                       .WhereIF(!currentUser.IsSuperAdmin, u => u.AccountType != AccountTypeEnum.SysAdmin)
                       .WhereIF(currentUser.IsSuperAdmin && input.TenantId > 0, u => u.TenantId == input.TenantId)
                       .WhereIF(!string.IsNullOrWhiteSpace(input.Account), u => u.Account.Contains(input.Account))
                       .WhereIF(!string.IsNullOrWhiteSpace(input.RealName), u => u.RealName.Contains(input.RealName))
                       .WhereIF(!string.IsNullOrWhiteSpace(input.PosName), (u, a, b) => b.Name.Contains(input.PosName))
                       .WhereIF(!string.IsNullOrWhiteSpace(input.Phone), u => u.Phone.Contains(input.Phone))
                       .OrderBy(u => new { u.OrderNo, u.Id })
                       .Select((u, a, b) => new UserOutput
                       {
                           OrgName = a.Name,
                           PosName = b.Name,
                           RoleName = SqlFunc.Subqueryable<SysUserRole>().LeftJoin<SysRole>((m, n) => m.RoleId == n.Id).Where(m => m.UserId == u.Id).SelectStringJoin((m, n) => n.Name, ","),
                           //DomainAccount = SqlFunc.Subqueryable<SysUserLdap>().Where(m => m.UserId == u.Id).Select(m => m.Account)
                       }, true)
                       .ToPagedListAsync(input.Page, input.PageSize);
        }
    }
}
